import os
import pickle

class ProvListManager(object):
    triggers = ["!provlist", "!prov", "!addprov", "!delprov"]
    channels = {}
    name = "provlist"
    help = ["Province listing commands:",
            "%c6!provlist%c"%(03,03),
            "%c6!addprov%c <ircnick> <province>"%(03,03),
            "%c6!delprov%c <ircnick>"%(03,03),
            "%c6!prov%c <part-of-name>"%(03,03)]
    
    def command(self, firstword, user, channel, msg):
        if not self.channels.has_key(channel):
            self.channels[channel] = ProvList(channel)
        
        provlist = self.channels[channel]
        if msg.lower() == "!provlist":
            return {'chanmsg': provlist.printProvs()}
        if firstword == "!addprov":
            words = msg.split()
            if len(words) < 3: return {'chanmsg':["Usage: !addprov <ircnick> <provname>"]}
            nick = words[1]
            provname = "".join(map(lambda word:"%s "%word, words[2:])).rstrip()
            if provname.startswith("- "): provname = provname[2:]
            return {'chanmsg': [provlist.add(nick, provname)]}
        if firstword == "!delprov":
            words = msg.split()
            if len(words) != 2: return {'chanmsg':["Usage: !delprov <ircnick>"]}
            nick = words[1]
            return {'chanmsg': [provlist.remove(nick)]}
        if firstword == "!prov":
            words = msg.split()
            if len(words) < 2: return {'chanmsg':["Usage: !prov <searchpattern>"]}
            pattern = "".join(map(lambda word:"%s "%word, words[1:])).rstrip()
            return {'chanmsg': provlist.search(pattern)}
        return {}
    


class ProvList(object):
    def __init__(self, channel):
        self.provs = {}
        self.filename = ".\\" + channel + "_provs.txt"
        if os.path.exists(self.filename):
            f = open(self.filename, 'r')
            self.provs = pickle.load(f)
            f.close()    
    
    def save(self):
        f = open(self.filename, 'w')
        pickle.dump(self.provs, f)
        f.close()

    def add(self, nick, provname):
        if len(self.provs) >= 30: return "Too many provs already listed."
        self.provs[nick] = provname
        self.save()
        return "Added: %s - %s"%(nick, provname)

    def remove(self, nick):
        if not self.provs.has_key(nick): return "%s not listed."%nick
        del self.provs[nick]
        self.save()
        return "Removed prov listing for %s."%(nick)
        
    def printProvs(self):
        if len(self.provs) == 0: return ["There are currently no provs listed."]
        nicks = self.provs.keys()
        nicks.sort(lambda x, y: cmp(x.lower(),y.lower()))
        return map(lambda nick: "%s - %s"%(nick, self.provs[nick]), nicks)
    
    def search(self, pattern):
        found = {}
        for k,v in self.provs.iteritems():
            if pattern.lower() in k.lower() or pattern.lower() in v.lower():
                found[k] = v
        return map(lambda k: "%s - %s"%(k, found[k]), found.keys())
